package com.yhy.admin.service.mng;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import com.yhy.admin.service.FtpConfigSetService;
import com.yhy.admin.vo.FtpConfigSet;
import com.yhy.common.utils.FileUtils;
import com.yhy.common.utils.SpringContextHolder;
import com.yhy.common.utils.YhyUtils;
import com.yhy.common.vo.SysAttachment;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 20-6-3 下午4:03 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2020<br>
 *  *
 *
 */

/**
 * <br>
 * <b>功能：</b><br>
 * <b>作者：</b>yanghuiyuan<br>
 * <b>日期：</b> 2020/3/19 <br>
 * <b>版权所有：<b>版权所有(C) 2020<br>
 */
@Component
public class FtpManageService {
    protected Logger LOGGER = LoggerFactory.getLogger(getClass());

    private Ftp ftp;

    private String code;
    public FtpManageService() {
        this.code = "SYSTEM";
    }

    public FtpManageService(String code) {
        this.code = code;
    }

    //上传开始
    public void begin() {
        FtpConfigSetService configSetService = SpringContextHolder.getBean(FtpConfigSetService.class);
        FtpConfigSet ftpConfigSet = configSetService.getFtpConfigByCode(this.code);
        ftp = new Ftp(ftpConfigSet.getIp(),ftpConfigSet.getPort(),ftpConfigSet.getUser(),ftpConfigSet.getPassword());
    }

    public void putAttachment(String directory, String fileName, File file) {
        directory = directory.startsWith("/") ? directory : "/" + directory;
        ftp.upload(directory,fileName,file);
    }

    public void downloadAttachment(String filePath, OutputStream outputStream) {
        String fileName = FileUtil.getName(filePath);
        String dir = StrUtil.removeSuffix(filePath, fileName);
        this.downloadAttachment(dir,fileName,outputStream);
    }

    public void downloadAttachment(String directory, String fileName, OutputStream outputStream) {
        directory = directory.startsWith("/") ? directory : "/" + directory;
        BufferedOutputStream outStream = null;
        try {
            outStream = new BufferedOutputStream(outputStream);
            ftp.download(directory, fileName, outputStream);
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    LOGGER.error("流关闭失败。");
                }
            }
        }

        ftp.download(directory, fileName, outputStream);
    }

    public void downloadAttachment(String filePath, File outputFile) {
        ftp.download(filePath, outputFile);
    }

    public void removeAttachment(String filePath) {
        ftp.delFile(filePath);
    }

    //上传结束
    public void end() {
        try {
            ftp.close();
        } catch (Exception e) {

        }
    }

    public Boolean upload(SysAttachment sysAttachment, MultipartFile multipartFile, Boolean isUploadFtp) {
        boolean rtn = true;
        File file = FileUtils.toFile(multipartFile);
        String fileName = multipartFile.getOriginalFilename();
        sysAttachment.setFileName(fileName);
        sysAttachment.setFilePath(file.getAbsolutePath());//返回对应的文件路径
        if(StringUtils.isBlank(sysAttachment.getFileName())) {
            sysAttachment.setFileName(file.getName());
        }
        sysAttachment.setFileType(FileUtils.getExtensionName(file.getName()));
        sysAttachment.setFileUrl("");
        sysAttachment.setFileSize(Double.valueOf(FileUtils.size(file)));
        sysAttachment.setCreateBy(sysAttachment.getCreateBy());
        sysAttachment.setEnableFlag("Y");
        sysAttachment.setLastUpdateBy(sysAttachment.getCreateBy());

        if(isUploadFtp) {
            try {
                //上传至 ftp
                String directory= "/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date());
                String ftpFileName = YhyUtils.generateUUID() + "." + sysAttachment.getFileType();
                sysAttachment.setFilePath(directory + "/" + ftpFileName);
                this.begin();
                this.putAttachment(directory, ftpFileName, file);
            } catch (Exception e) {
                rtn = false;
            } finally {
                //删除临时文件
                FileUtils.deleteFile(file);
                this.end();
            }
        }
        return rtn;
    }

}
